<template>
  <ul>
    <li>ID: {{$route.params.id}}</li>
    <li>Title: {{state.detail.title}}</li>
    <li>Content: {{state.detail.content}}</li>
  </ul>
</template>

<script lang="ts">
  export default {
    name: 'MessageDetail'
  }
</script>
<script lang="ts" setup>
import { onMounted, reactive, watch } from 'vue';
import { useRoute } from 'vue-router';

interface MessageDetail {
  id: number;
  title: string;
  content: string;
}
const allMessageDetils: MessageDetail[] = [
  {id: 1, title: 'message001', content: 'message content001'},
  {id: 3, title: 'message003', content: 'message content003'},
  {id: 4, title: 'message004', content: 'message content004'},
]

// 也可以读取props映射的数据
const props = defineProps({
  id: Number,
  name: String
})

const state = reactive<{detail: MessageDetail}>({
  detail: {} as MessageDetail
})

const route = useRoute()
onMounted(() => {
  setTimeout(() => {
    // 得到当前id
    const id = +route.params.id
    const detail = allMessageDetils.find(detail => detail.id===id)
    state.detail = detail as MessageDetail
  }, 1000);
})

// 监视params
watch(() => route.params, (newParams) => {
  // 对路由变化作出响应...
  setTimeout(() => {
    // 得到当前新的id
    const id = +newParams.id
    const detail = allMessageDetils.find(detail => detail.id===id)
    state.detail = detail as MessageDetail
  }, 1000);
})

</script>

<style scoped>

</style>
